package cn.alex.sso.framework.global;

import cn.alex.sso.framework.core.Result;
import cn.alex.sso.framework.util.StreamUtils;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.SaTokenException;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Objects;

/**
 * 全局异常处理
 *
 * @author Alex
 * @date 2024/9/25 00:53
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * SaToken 异常拦截跳转消息通知页
     */
    @ExceptionHandler(SaSsoExceptionMsg.class)
    public ModelAndView saSsoException(SaSsoExceptionMsg e) {
        ModelAndView mv = new ModelAndView("message.html");
        mv.addObject("code", e.getCode());
        mv.addObject("msg", e.getMessage());
        return mv;
    }

    /**
     * SaToken 全局异常拦截
     */
    @ExceptionHandler(SaTokenException.class)
    public Result<Void> saSsoException(SaTokenException e) {
        return Result.set(e.getCode(), e.getMessage());
    }

    /**
     * SaToken 全局异常拦截（拦截项目中的NotLoginException异常）
     */
    @ExceptionHandler(NotLoginException.class)
    public Result<Void> notLoginException(NotLoginException e) {
        return Result.set(401, "当前会话未登录，请登录后重试");
    }


    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<Void> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
        log.error("请求地址'{}',不支持'{}'请求", request.getRequestURI(), e.getMethod());
        return Result.set(HttpStatus.HTTP_BAD_METHOD, StrUtil.format("当前请求不支持 {} 请求", e.getMethod()));
    }

    /**
     * 主键或UNIQUE索引，数据重复异常
     */
    @ExceptionHandler(DuplicateKeyException.class)
    public Result<Void> handleDuplicateKeyException(DuplicateKeyException e, HttpServletRequest request) {
        String requestUrl = request.getRequestURI();
        log.error("请求地址'{}',数据库中已存在记录'{}'", requestUrl, e.getMessage());
        return Result.warn("数据库中已存在该记录，请联系管理员确认");
    }

    /**
     * Http请求消息序列化异常
     */
    @ExceptionHandler({HttpMessageNotReadableException.class})
    public Result<Void> messageExceptionHandler(HttpMessageNotReadableException e) {
        log.error("http请求参数转换异常: {}", e.getMessage());
        return Result.set(HttpStatus.HTTP_BAD_REQUEST, "请求参数错误，请联系管理员");
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public Result<Void> handleServiceException(ServiceException e) {
        log.error(e.getMessage(), e);
        Integer code = e.getCode();
        return ObjUtil.isNotNull(code) ? Result.set(code, e.getMessage()) : Result.err(e.getMessage());
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public Result<Void> handleBindException(BindException e) {
        String message = StreamUtils.join(e.getAllErrors(), DefaultMessageSourceResolvable::getDefaultMessage, ", ");
        return Result.warn(message);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result<Void> constraintViolationException(ConstraintViolationException e) {
        String message = StreamUtils.join(e.getConstraintViolations(), ConstraintViolation::getMessage, ", ");
        return Result.warn(message);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String message = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();
        return Result.warn(message);
    }

    /**
     * 系统异常
     */
    @ExceptionHandler({Exception.class, NullPointerException.class, RuntimeException.class})
    public Result<Void> handleException(Exception e, HttpServletRequest request) {
        log.error("请求地址'{}',发生系统异常.", request.getRequestURI(), e);
        return Result.set(HttpStatus.HTTP_INTERNAL_ERROR, "系统繁忙，请稍后重试");
    }
}
